package com.example.userregist;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

//创建数据库
public class UserDatabaseHelper extends SQLiteOpenHelper
{
    private Context context;
    //上下文？
    public UserDatabaseHelper(Context context)
    {
        super(context,"myuser.db",null,1);
        this.context=context;
    }
    //运行一次，创建数据表
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE information(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name VARCHAR(20),password VARCHAR(20))");
    }
    //更新数据表
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    //插入
    public long insert(String name,String password)
    {
        //获得对数据库操作的权限（读写）
        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();

        ContentValues values=new ContentValues();
        values.put("name",name);
        values.put("password",password);
        //获得插入数据的id
        long id=sqLiteDatabase.insert("information",null,values);
        if(id!=0)
        {
            Toast.makeText(context,"添加成功",Toast.LENGTH_SHORT).show();
        }
        //关闭数据库连接
        sqLiteDatabase.close();
        return id;
    }
    //查询
    public boolean queryforLogin(String name,String password)
    {
        //获得对数据库操作的权限（可读）
        SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
        Cursor cursor= sqLiteDatabase.query("information",null,"name=? and password=?",
                new String[]{name,password},null,null,null);
        if(cursor.getCount()==0)
        {
            //关闭指针
            cursor.close();
            //关闭数据库连接
            sqLiteDatabase.close();
            return false;
        }
        else
        {
            cursor.close();
            sqLiteDatabase.close();
            return true;
        }
    }

}
